﻿using Common.Models;
using Common.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography.Xml;
using Wallpaper.Models.DTOs.Requests.User;
using Wallpaper.Models.DTOs.Responses.User;
using Wallpaper.Models.DTOs.WeChatLogin.Request;
using Wallpaper.Models.DTOs.WeChatLogin.Responses;
using Wallpaper.Services.IService;
using Wallpaper.Services.Service;

namespace WallpaperApi.Controllers
{
    [Route("api/users")]
    [ApiController]
    public class UsersController : BaseController
    {
        private readonly IWeChatService _weChatService;
        private readonly IJwtService _jwtService;
        private readonly IUserService _userService;
        readonly ILogger<UsersController> _logger;

        public UsersController(IWeChatService weChatService, IJwtService jwtService, IUserService userService, ILogger<UsersController> logger)
        {
            _weChatService = weChatService;
            _jwtService = jwtService;
            _userService = userService;
            _logger = logger;
        }


        /// <summary>
        /// 微信用户授权登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("wechat-login")]
        public async Task<ApiResponse<WeChatLoginResponse>> WeChatLogin([FromBody] WeChatLoginRequest request)
        {
            
                // 获取客户端IP
                var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
                // 1. 通过code获取微信会话信息
                var wechatInfo = await _weChatService.CodeToSessionAsync(request.Code);
            // 2. 获取或创建用户
            // 2. 获取或创建用户 - 传递昵称和头像
                var user = await _weChatService.GetOrCreateUserAsync(
                    wechatInfo,
                    ipAddress,
                    request.Nickname,    // 添加这些参数
                    request.AvatarUrl
                );
            // 3. 生成JWT Token
            var token = _jwtService.GenerateToken(user);
                // 4. 返回响应
                var response = new WeChatLoginResponse
                {
                    Token = token,
                    User = new UserLoginResponse
                    {
                        Id = user.Id,
                        Nickname = user.Nickname,
                        AvatarUrl = user.AvatarUrl,
                        Gender = user.Gender,
                        Points = user.Points,
                        TodayFreeDownloadCount = user.TodayFreeDownloadCount,
                        Signature=user.Signature
                    }
                };
                return ApiResponse<WeChatLoginResponse>.Success(response);
        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResponse<Object>> Update([FromBody] UpdateUserRequest request)
        {
             bool userInfo=await _userService.UpdateAsync(request, UserId);
             return ApiResponse<Object>.Success();
        }

        /// <summary>
        /// 获取登录用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("get")]
        public async Task<ApiResponse<UserAppLoginResponse>> Get()
        {
            UserAppLoginResponse user = await _userService.GetByIdAsync(UserId);

            return ApiResponse<UserAppLoginResponse>.Success(user);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="queryRequest"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize("system:users:query")]  // 需要查询权限
        public async Task<ApiResponse<PagedResult<UserManagementResponse>>> Page([FromQuery] UserQueryRequest queryRequest)
        {
            PagedResult<UserManagementResponse> pagedResult = await _userService.PageAsync(queryRequest);
            return ApiResponse<PagedResult<UserManagementResponse>>.Success(pagedResult);
        }


        /// <summary>
        /// 根据id删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ApiResponse<Object>> Delete(string id)
        {
            bool result = await _userService.DeleteAsync(id);
            _logger.LogInformation($"用户删除成功 - 操作者:{Account}删除用户ID：{id}的角色信息");
            return ApiResponse<Object>.Success();
        }

        /// <summary>
        /// 用户签到
        /// </summary>
        /// <returns></returns>
        [HttpPut("checkin")]
        public async Task<ApiResponse<Object>> Checkin()
        {
            await  _userService.CheckinAsync(UserId);
            return ApiResponse<Object>.Success();
        }  




    }
}
